import { constantRoutes } from '@/router'
// import { getUserPermissions } from '@/api/user'
import { asyncRoutes } from '@/router/asyncRoutes'

const state = {
  routes: [],
  addRoutes: [],
  permissions: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  SET_PERMISSIONS: (state, permissions) => {
    state.permissions = permissions
  }
}

const actions = {
  generateRoutes({ commit }) {
    return new Promise(async (resolve, reject) => {
      try {
        // 获取用户权限
        // const { permissions } = await getUserPermissions()
        const permissions = ['system:user:list', 'system:role:list', 'system:menu:list', 'tool:gen:list', 'tool:swagger:list']
        // 保存权限
        commit('SET_PERMISSIONS', permissions)
        
        // 过滤有权限的路由
        const accessedRoutes = filterAsyncRoutes(asyncRoutes, permissions)
        
        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)
      } catch (error) {
        console.error('生成路由失败:', error)
        reject(error)
      }
    })
  }
}

// 递归过滤异步路由表
function filterAsyncRoutes(routes, permissions) {
  const res = []
  
  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(permissions, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, permissions)
      }
      res.push(tmp)
    }
  })
  
  return res
}

// 判断是否有权限
function hasPermission(permissions, route) {
  if (route.meta && route.meta.permissions) {
    return permissions.some(permission => 
      route.meta.permissions.includes(permission)
    )
  }
  return true
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
} 